// subcontract/Message/conversation/index.js
import Socket from './socket'
import { dateTimeFormat, emoji, getRect } from './time'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    emoji,
    showEmoji: false,
    local: getApp().local,
    socket: {},//Socket实例
    shopId: '',//商家id
    goodsId: '',//商家id
    pageStatus: 'loading',
    scrollTop: '',
    intoView: '',
    page: 1,
    recoreds: [],//消息列表
    serveinfo: {},//客服信息
    text: '',
    Current: Date.now(),
    scrollTop: '',
  },
  scrollToupper() {
    this.getChatRecord()
  },
  handleEmojiInput(event) {
    let { text } = event.currentTarget.dataset
    this.setData({
      text: this.data.text + text
    })
  },
  /**选取图片 */
  async chooseImage() {
    const { errMsg, tempFiles } = await wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      camera: 'back',
    })
    if (errMsg == 'chooseMedia:ok') {
      this.uploadFilePromise(tempFiles[0].tempFilePath)
    }
  },
  /**上传营业执照 */
  async uploadFilePromise(url) {
    const { code, data } = await getApp().api.uploadFilePromise(url)
    if (code == 1) {
      this.send(data.uri, 2)
    }
  },
  /**回显输入 */
  onChengInput(event) {
    this.setData({ text: event.detail.value })
  },
  /**发送文本 */
  sendText() {
    let { text } = this.data
    if (!text) return
    this.send(text, 1)
    this.setData({ text: '' })
  },
  // 发送消息
  send(msg, type) {
    let { serveinfo } = this.data
    this.socket.send({
      event: 'chat',
      data: {
        msg,
        msg_type: type, // 暂定 1=>文本；2=>图片；3=>表情
        to_id: serveinfo.id, // 接收人id；客服发给用户则为user_id, 用户发给客服则为kefu_id
        to_type: "kefu"
      }
    })
  },
  /**发送商品 */
  sendGoods() {
    // this.showGoods = false
    this.send(this.goodsId, 3)
  },
  /** 登录成功，发送用户上线通知 */
  loginEvent(data) {
    let { serveinfo } = this.data
    this.socket.send({
      event: 'user_online',
      data: {
        kefu_id: serveinfo.id
      }
    })
  },
  toggleEmoji: function () {
    this.setData({
      showEmoji: !this.data.showEmoji
    });
  },
  // 初始化
  init() {
    let { shopId, local, serveinfo } = this.data
    this.socket = new Socket(local.get('config').ws_domain, {
      token: local.get('token'),
      type: 'user',
      client: 1,
      shop_id: shopId,
    })
    this.socket.addEvent('connect', () => {
      this.setTitle('连接中...')
    })
    this.socket.addEvent('open', () => {
      this.setTitle(serveinfo.nickname)
      // this.isError = false
    })
    this.socket.addEvent('message', (data) => {
      switch (data.event) {
        case 'login':
          this.loginEvent(data.data)
          break;
        case 'chat':
          this.chatEvent(data.data)
          break;
        case 'transfer':
          this.transferEvent(data.data)
          break;
        case 'error':
          this.errorEvent(data.data)
          break;

      }
    })
    this.socket.addEvent('error', (data) => {
      // getApp().showToast('连接失败')
      this.setTitle('连接失败')
      console.log('连接失败');
    })
  },
  chatEvent(data) {
    console.log(data);
    let { recoreds, shopId } = this.data
    this.isError = false
    if (data.from_type == 'kefu') {
      wx.vibrateLong({
        success: function () {
          console.log('success');
        }
      });
    }
    if (data.shop_id != shopId) {
      return
    }
    recoreds.push(data)
    console.log(recoreds);
    this.setData({ recoreds })
    setTimeout(() => {
      getRect('#bottom').then(res => {
        if (res.bottom < 1000) {
          this.scrollToItem(data.id)
        }
      })
    }, 0)
  },
  getConfig() {
    return getApp().api.getChatConfig({
      shop_id: this.data.shopId
    }).then(res => {
      return Promise.resolve(res)
    }).catch(() => {
      return Promise.reject()
    })
  },
  // 获取数据
  async getData() {
    let { serveinfo } = this.data
    try {
      const res = await this.getConfig()
      if (res.code == 0) return getApp().showToast(res.msg)
      await this.getChatRecord()
      this.getGoods()
      this.scrollToBottom()
    } catch (e) {
      console.error(e);
    }
  },
  /** 获取商品信息 */
  async getGoods() {
    let { goodsId, serveinfo } = this.data
    if (!goodsId) return
    let object = {
      goods_id: goodsId
    }
    const { code, data } = await getApp().api.getGoodsDetail(object)
    if (code == 1) {
      this.setData({ goodsInfo: data })
      if (serveinfo.id) {
        this.setData({ showGoods: true })
      }
    }
  },
  /**获取聊天记录 */
  async getChatRecord() {
    const { page, pageStatus, shopId, recoreds } = this.data
    if (pageStatus == 'finish') return
    const res = await getApp().api.chatRecord({
      shop_id: shopId,
      page_no: page
    })
    if (res.code == 1) {
      let toid = 0
      const {
        kefu,
        record
      } = res.data
      this.setData({
        page: (this.data.page * 1) + 1,
        serveinfo: kefu,//客服信息
        showIndex: record.list.length,//this.showIndex = 
      })
      recoreds.unshift(...record.list)

      recoreds.map(item => {
        item.time = dateTimeFormat(item.create_time_stamp * 1000)
        // item.show_time = 
        return item
      })
      this.setData({
        recoreds,
      })
      setTimeout(() => {
        if (!record.more) {
          this.setData({ pageStatus: 'finish' })
        }
        this.scrollToItem(toid)
        this.setData({ showIndex: -1 })
      }, 0);
      this.init()
      if (!kefu.id) {
        this.setTitle('客服不在线')
        console.log('客服不在线');
        getApp().showToast('客服不在线')
        return
      }
      this.socket.connect()
    }
  },
  scrollToBottom() {
    this.setData({ intoView: `bottom` })
    setTimeout(() => {
      this.setData({ intoView: '' })
    }, 0);
  },
  scrollToItem(id) {
    this.setData({ intoView: `chat-item_${id}` })
    setTimeout(() => {
      this.setData({ intoView: '' })
    }, 0);
  },
  setTitle(title) {
    wx.setNavigationBarTitle({
      title
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      shopId: options.shop_id || 0,
      goodsId: options.goods_id
    })

    this.getData()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.socket.close()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})